<template>
  <a-modal v-model:visible="visible" title="批量编辑图片" :footer="false" @cancel="closeModal">
    <a-typography-paragraph type="secondary">* 只对当前页面的图片生效</a-typography-paragraph>
    <!-- 表单项 -->
    <a-form layout="vertical" :model="formData" @finish="handleSubmit">
      <a-form-item label="分类" name="category">
        <a-auto-complete
          v-model:value="formData.category"
          :options="categoryOptions"
          placeholder="请输入分类"
          allowClear
        />
      </a-form-item>
      <a-form-item label="标签" name="tags">
        <a-select
          v-model:value="formData.tags"
          :options="tagOptions"
          mode="tags"
          placeholder="请输入标签"
          allowClear
        />
      </a-form-item>
      <a-form-item label="命名规则" name="nameRule">
        <a-input
          v-model:value="formData.nameRule"
          placeholder="请输入命名规则，输入「序号」可动态生成"
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">提交</a-button>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup lang="ts">
import { editPictureByBatchUsingPost, getTagCategoryUsingGet } from '@/api/pictureController'
import { message } from 'ant-design-vue'
import { onMounted, ref, withDefaults } from 'vue'
//定义组件类型的属性
interface Props {
  pictureList: API.PictureVO[]
  spaceId: number
  onSuccess: () => void
}
const props = withDefaults(defineProps<Props>(), {})

//控制弹窗显示
const visible = ref(false)

//打开弹窗
const openModal = () => {
  visible.value = true
}

//关闭弹窗
const closeModal = () => {
  visible.value = false
}

//暴露函数给父组件
defineExpose({
  openModal,
})

//表单数据
const formData = ref({
  category: '',
  tags: [],
  nameRule: '',
})

const categoryOptions = ref<string[]>([])
const tagOptions = ref<string[]>([])

//获取分类和标签
const convertToSelectOptions = (list: string[]) => {
  return list.map((item) => ({
    label: item,
    value: item,
  }))
}
const getTagCategoryOptions = async () => {
  const res = await getTagCategoryUsingGet()
  const { code, data } = res?.data
  if (code === 0 && data) {
    categoryOptions.value = convertToSelectOptions(data?.categoryList ?? [])
    tagOptions.value = convertToSelectOptions(data?.tagList ?? [])
  } else {
    message.error('加载失败' + res.data.message)
  }
}

//提交表单
const handleSubmit = async (values: any) => {
  if (!props.pictureList) {
    return
  }
  const res = await editPictureByBatchUsingPost({
    pictureIdList: props.pictureList.map((item) => item.id),
    spaceId: props.spaceId,
    ...values,
  })
  if (res.data.code === 0) {
    message.success('批量编辑成功')
    console.log('批量编辑结果', res)
    props.onSuccess()
    closeModal()
  } else {
    message.error('操作失败' + res.data.message)
  }
}
onMounted(() => {
  getTagCategoryOptions()
})
</script>
